package org.acmclass.fatworm.test.result;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.acmclass.fatworm.test.FatTestException;
import org.acmclass.fatworm.test.plaintext.FatFileWriter;
import org.acmclass.fatworm.test.plaintext.Tag;
import org.acmclass.fatworm.test.sql.SQLWithOptions;

public class AnswerGenerator extends ResultConsumer {

	public static final String EMPTY_RESULT = "# EMPTY";

	private FatFileWriter writer;
	private Map<Integer, List<String>> answers = Collections
			.synchronizedMap(new HashMap<Integer, List<String>>());
	private Map<Integer, List<String>> queryAns = Collections
			.synchronizedMap(new HashMap<Integer, List<String>>());

	public AnswerGenerator(String filename) throws FatTestException {
		writer = new FatFileWriter(filename);
	}

	@Override
	public void setSQL(int threadID, SQLWithOptions sql) {
		super.setSQL(threadID, sql);
		for (String line : sql.getSql().split("\n")) {
			addToList(answers, threadID, "# ".concat(line));
		}
	}

	private synchronized void checkListExist(Map<Integer, List<String>> map,
			int threadID) {
		if (!map.containsKey(threadID)) {
			map.put(threadID, new ArrayList<String>());
		}
	}

	private void addToList(Map<Integer, List<String>> map, int threadID,
			String line) {
		checkListExist(map, threadID);
		map.get(threadID).add(line);
	}

	@Override
	protected void processLineString(int threadID, String resultLine) {
		addToList(queryAns, threadID, resultLine);
	}

	@Override
	public void processQueryFinal(int threadID) throws SQLException {
		checkListExist(queryAns, threadID);
		List<String> ans = queryAns.get(threadID);
		if (ans.size() == 0)
			ans.add(EMPTY_RESULT);
		if (!sqls.get(threadID).isOrdered()) {
			Collections.sort(ans);
		}
		addToList(queryAns, threadID, ";");
		checkListExist(answers, threadID);
		answers.get(threadID).addAll(ans);
		queryAns.remove(threadID);
	}

	@Override
	public void close() throws FatTestException {
		for (int i = 0; i < answers.size(); ++i) {
			writer.writeTag(Tag.NEW_THREAD);
			for (String line : answers.get(i))
				writer.writeLine(line);
		}
		writer.close();
	}

	@Override
	public String getResult() {
		return null;
	}

}
